//app.js
import {launch_exec} from './utils/launch_exec'

App({
  onLaunch: function (options) {
    launch_exec()
  },
  onShow: function (options){

  },
  onHide: function(){

  },
  onError: function(msg){

  },
  globalData: {
    userInfo: null,
    session: '',
    select_family_id: -1,  //当前选中的family_id
  },

  formatTime(time) {
    if (typeof time !== 'number' || time < 0) {
      return time
    }
  
    const hour = parseInt(time / 3600, 10)
    time %= 3600
    const minute = parseInt(time / 60, 10)
    time = parseInt(time % 60, 10)
    const second = time
  
    return ([hour, minute, second]).map(function (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join(':')
  },
  
  formatLeadingZeroNumber(n, digitNum = 2) {
    n = n.toString()
    const needNum = Math.max(digitNum - n.length, 0)
    return new Array(needNum).fill(0).join('') + n
  },
  
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
  
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
  
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i], 10)
      const num2 = parseInt(v2[i], 10)
  
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
  
    return 0
  },

  //发送http请求，自带session.
  httpRequest: function (method, data_obj, success_cb, fail_cb) {
    data_obj = data_obj || {}
    success_cb = success_cb || function(){}
    fail_cb = fail_cb || function(){}

    wx.showLoading({
      title: '加载中',
    })

    wx.request({
      url: this.globalConfig.getServerUrl(),
      method: 'POST',
      header: { 'content-type': 'application/json'},
      data: {
        method: method,
        json: JSON.stringify(data_obj),
        session: this.globalData.session
      },
      success: (res) => {
        wx.hideLoading()
        if (res.data && res.data.code == 0) {
          //返回成功
          success_cb(res.data.data)
        }else{
          //返回错误
          res.fail_type = 0  //正常返回的错误
          res.code = res.data.code
          res.errMsg = res.data.msg
          res.code_msg = ''
          if (res.code == -1) {
            res.code_msg = '服务器返回异常'
            res.code_msg = ''
          }else if (res.code == -2) {
            res.code_msg = '参数错误'
          }else if (res.code == -3) {
            res.code_msg = '数据库访问异常'
          }else if (res.code == -4) {
            res.code_msg = 'session错误'
          }else if (res.code == -5) {
            res.code_msg = 'session过期'
          }else if (res.code == -6) {
            res.code_msg = 'http相关错误'
          }else if (res.code == -7) {
            res.code_msg = '请求后台崩溃'
          }

          let tip = ""
          if (res.code_msg.length > 0) {
            tip += "请求失败："
            tip += res.code_msg + "-"
          }
          tip += res.errMsg

          let obj = fail_cb(res)
          //根据失败回调的返回判断是否弹出错误信息
          if (typeof(obj) == "object" && obj.notip) {
          } else {
            this.showTip(tip)
          }
        }
      },
      fail: (res) => {
        wx.hideLoading()
        res.fail_type = 1  //请求异常错误

        let obj = fail_cb(res)
        //根据失败回调的返回判断是否弹出错误信息
        if (typeof(obj) == "object" && obj.notip) {
        } else {
          this.showTip("请求异常：" + JSON.stringify(res))
        }
      }
    })
  },

  showTip: function (msg) {
    wx.showToast({
        title: msg,
        icon: 'none',
        duration: 3000
    });
  },

  showOkTip: function (msg) {
    wx.showToast({
        title: msg,
        icon: 'success',
        duration: 2000
    });
  },

  globalConfig: {
    domain: '127.0.0.1',   //121.196.167.174
    curr_person: null,   //当前登录人ID
    getServerUrl: function() {
      //服务器请求地址
      return 'http://' + this.domain + ':8000/form'
    },
    getPicUrl: function(){
      //图片访问地址
      return 'http://' + this.domain + ':8088'
    },
    getPicEditUrl: function(){
      //图片编辑地址
      return 'http://' + this.domain + ':8001'
    },
  },

  //跳到textarea编辑页: 输入初始text; 编辑后的回调函数，该函数接收编辑后的字符串作为入参; textarea展示的placeholder
  navigateToTextAreaPage(init_text, confirm_cb, placehoder='') {
    this.textarea_page_init_text = init_text
    this.textarea_page_confirm_cb = confirm_cb
    this.textarea_page_placeholder = placehoder
    wx.navigateTo({
      url: '/pages/help/textarea'
    })
  },

  //调到其他家族选择页：选择其他家族中的人（先选择家族，再选择人）
  //入参： 选择某个性别的人（0女， 1男，其他值 不限）、选择回调,回调参数familyId, personId
  navigateToOtherFamilyMember(sex, select_cb) {
    this.other_family_member_select_sex = sex
    this.other_family_member_select_cb = select_cb
    wx.navigateTo({
      url: '/pages/help/select_other_family'
    })
  }

})